<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\BaseModel;
use App\Service\Kms\Home\HomeService;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class OpenShopAddressModel extends BaseModel
{
    protected $table = 'open_shop_address';

    protected $fillable = [
        'orderNo',
        'provinceCode',
        'cityCode',
        'areaCode',
        'addressPrefix',
        'addressDetail',
    ];

    public function addData(): Model
    {
        $arr = [];
        foreach ($this->fillable as $field) {
            if ($this->$field === null) {
                continue;
            }

            $arr[$field] = $this->$field;
        }

        return self::query()->updateOrCreate(['orderNo' => $this->orderNo], $arr);
    }

    /**
     * 自动刷新地址
     * @param string $orderNo
     * @param OpenShopSignOrderModel|null $signOrderModel
     * @return bool
     */
    public static function autoAdd(string $orderNo, ?OpenShopSignOrderModel $signOrderModel = null): ?Model
    {
        if (!$signOrderModel) {
            $signOrderModel = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();
        }

        if (!$signOrderModel) {
            return null;
        }

        $arr = [];
        if (MissionTemplateService::getSortByStepStatus($signOrderModel->progressRel->nowStepStatus ?? 0) >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_5)) {

            $arr = [
                'orderNo'       => $orderNo,
                'provinceCode'  => $signOrderModel->siteLocationRel['provinceCode'] ?? '',
                'cityCode'      => $signOrderModel->siteLocationRel['cityCode'] ?? '',
                'areaCode'      => $signOrderModel->siteLocationRel['areaCode'] ?? '',
                'addressPrefix' => $signOrderModel->siteLocationRel['cityArea'] ?? '',
                'addressDetail' => $signOrderModel->siteLocationRel['address'] ?? '',
            ];
        }

        if (!isset($arr['provinceCode']) || !$arr['provinceCode']) {
            $arr = [
                'orderNo'       => $orderNo,
                'provinceCode'  => $signOrderModel->baseInfoRel['chooseShopProvinceCode'] ?? '',
                'cityCode'      => $signOrderModel->baseInfoRel['chooseShopCityCode'] ?? '',
                'areaCode'      => $signOrderModel->baseInfoRel['chooseShopDistrictCode'] ?? '',
                'addressPrefix' => $signOrderModel->baseInfoRel['chooseShopAddressPrefix'] ?? '',
                'addressDetail' => $signOrderModel->baseInfoRel['shopAddress'] ?? '',
            ];
        }

        OpenShopSignOrderPermissionAnchorModel::query()
                                              ->where('orderNo', $orderNo)
                                              ->update([
                                                  'provinceCode' => $arr['provinceCode'],
                                                  'cityCode'     => $arr['cityCode'],
                                                  'districtCode' => $arr['areaCode']
                                              ]);

        return (new OpenShopAddressModel($arr))->addData();
    }

    public static function getData(string $orderNo)
    {
        return self::query()->where('orderNo', $orderNo)->first();
    }

    /**
     * 首页查询条件构造
     *
     * @param int $regionSelectionType
     * @param string $region
     * @param string $regionValue
     * @return Builder|mixed
     */
    public static function buildHomeSearchQuery(int $regionSelectionType, string $region, string $regionValue)
    {
        $query = function ($query) {
            $query->where("id", 0);
        };
        switch ($regionSelectionType) {
            case HomeService::REGION_SELECTION_TYPE_1:
                $region = attributeGet(
                    OpenShopOrganizationManageModel::allOrganizationManage()
                                                   ->where("type", "<>",
                                                       OpenShopOrganizationManageModel::HEADQUARTERS_ID)
                                                   ->where("name", $region)
                                                   ->first(),
                    "regionRel",
                    collect([])
                );

                if ($provinceCodes = $region->pluck("provinceCode")->toArray()) {
                    $query = function ($query) use ($provinceCodes) {
                        return $query->whereIn("provinceCode", $provinceCodes);
                    };
                }
                break;
            case HomeService::REGION_SELECTION_TYPE_2:
                $query = function ($query) use ($regionValue) {
                    return $query->where("provinceCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_3:
                $query = function ($query) use ($regionValue) {
                    return $query->where("cityCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_0:
                $query = null;
                break;
        }
        return self::query()->when($query, function ($subQuery) use ($query) {
            return $subQuery->where($query);
        });
    }
}
